import { defineStore } from "pinia";
import { ref } from "vue";
import { AddFriendListItem } from "./types/type";

let addressBookStore = defineStore('addressBook', () => {
  let addressBookUnReadCount = ref(0)
  if (localStorage.getItem('addressBookUnReadCount')) {
    addressBookUnReadCount.value = Number(localStorage.getItem('addressBookUnReadCount'))
  }
  let addFriendList = ref<AddFriendListItem[]>([])
  if (localStorage.getItem('addFriendList')) {
    addFriendList.value = JSON.parse(localStorage.getItem('addFriendList') as string)
  }
  const addUnReadCount = (item: AddFriendListItem) => {
    let isExist = false
    addFriendList.value.forEach((e) => {
      if (item.fromId === e.fromId && item.toId === e.toId) {
        isExist = true
      }
    })
    if (isExist) return
    addressBookUnReadCount.value++
    localStorage.setItem('addressBookUnReadCount', String(addressBookUnReadCount.value))
  }
  const reduceUnReadCount = () => {
    addressBookUnReadCount.value--
    localStorage.setItem('addressBookUnReadCount', String(addressBookUnReadCount.value))
  }
  const updateAddFriendList = (item: AddFriendListItem) => {
    let isExist = false
    addFriendList.value.forEach((e) => {
      if (item.fromId === e.fromId && item.toId === e.toId) {
        isExist = true
      }
    })
    if (isExist) return
    // 0 默认 1 已同意 2 已拒绝
    item.status = 0
    addFriendList.value.unshift(item)
    localStorage.setItem('addFriendList', JSON.stringify(addFriendList.value))
  }
  const updateItemStatus = (index: number, status: number) => {
    addFriendList.value[index].status = status
    localStorage.setItem('addFriendList', JSON.stringify(addFriendList.value))
  }
  return {
    addressBookUnReadCount,
    addFriendList,
    addUnReadCount,
    reduceUnReadCount,
    updateAddFriendList,
    updateItemStatus
  }
})

export default addressBookStore